package com.uenpay.im.ui.old.activity.dynamic;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.text.TextUtils;

/**
 * serializer dynamics
 * 
 * @author SL
 * @copyRight http://www.qiyunxin.com
 * 
 */
public class DynamicSerializer {
	public static DynamicEntity deserializeDynamicEntity(JSONObject json) {
		DynamicEntity dynamic = new DynamicEntity();
		dynamic.custid = json.optString("custid");
		dynamic.nickname = json.optString("nickname");
		dynamic.dynamicid = json.optString("dynamicid");
		dynamic.content = json.optString("content");
		dynamic._praise = json.optInt("_praise");
		dynamic.createtime = json.optString("createtime");
		JSONArray likeArray = json.optJSONArray("praiselist");
		if (likeArray != null) {
			dynamic.like_list = PraiseSerializer.deserializeUsers(likeArray);
		}
		JSONArray replyArray = json.optJSONArray("replylist");
		if (replyArray != null) {
			dynamic.reply_list = ReplySerializer.deserializeUsers(replyArray);
		}
		JSONObject jsonObject = json.optJSONObject("video");
		if (jsonObject != null) {
			dynamic.videoFileMessage = desFileMessage(jsonObject);
		}
		JSONObject object = json.optJSONObject("video_cover");
		if (object != null) {
			dynamic.videoConverFileMessage = desFileMessage(object);
		}
		JSONArray fileArray = json.optJSONArray("files");
		if (fileArray != null) {
			for (int i = 0, size = fileArray.length(); i < size; i++) {
				dynamic.files.add(desFileMessage(fileArray.optJSONObject(i)));
			}
		}
		return dynamic;
	}

	public static ArrayList<DynamicEntity> deserializeDynamicEntitys(JSONArray json) {
		ArrayList<DynamicEntity> Dynamics = new ArrayList<DynamicEntity>();
		for (int i = 0; i < json.length(); i++) {
			JSONObject jsonObject = json.optJSONObject(i);
			if (jsonObject != null) {
				if (!TextUtils.isEmpty(deserializeDynamicEntity(jsonObject).custid)
						&& !TextUtils
								.isEmpty(deserializeDynamicEntity(jsonObject).dynamicid)) {
					Dynamics.add(deserializeDynamicEntity(jsonObject));
				}
			}
		}
		return Dynamics;
	}

	private static FileMessage desFileMessage(JSONObject json) {
		FileMessage fileMessage = new FileMessage();
		fileMessage.fileid = json.optString("fileid");
		fileMessage.filehash = json.optString("filehash");
		return fileMessage;
	}
}
